package com.cloudbroker.bcs.common.aspect;

import static com.alibaba.fastjson.JSON.parseObject;
import static com.alibaba.fastjson.JSON.toJSONString;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cloudbroker.bcs.common.entity.HSBCPSBackVO;
import com.cloudbroker.bcs.common.exception.HSBCSErrInfoException;
import com.cloudbroker.bcs.common.util.PrintUtil;
import com.cloudbroker.bcs.common.util.ReflectionUtil;
import com.cloudbroker.bcs.common.util.VOUtil;

import java.util.HashMap;
import java.util.Map;

public class ExceptionHandleAspect {
    
    private static final String CLASS_NAME = ExceptionHandleAspect.class.getName();
    
    private static final Logger LOGGER = LoggerFactory.getLogger(CLASS_NAME);
    
    public ExceptionHandleAspect() {
        PrintUtil.printComponentLoaded(LOGGER, CLASS_NAME);
    }
    
    public Object handleException(ProceedingJoinPoint pjp) throws Throwable {
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Class<?> returnType = signature.getReturnType();
        Object result = null;
        try {
            result = pjp.proceed();
        } catch (HSBCSErrInfoException e) {
            LOGGER.error("execute failed", e);
            result = VOUtil.genErrorResult(e);
        }catch (Exception e) {
            LOGGER.error("execute failed", e);
            result = VOUtil.genCommonErrorResult();
        }
        if(ReflectionUtil.isSubClass(returnType , HSBCPSBackVO.class) ) {
            result = parseObject(toJSONString(result) , returnType);
        }
        return result;
    }

    public Object doException(JoinPoint pjp, Exception e) {
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Class<?> returnType = signature.getReturnType();
        if (e != null) {
            String errMsg = e.getMessage();
            int pos = errMsg.indexOf("|");
            if (pos != -1) {
                if (ReflectionUtil.isSubClass(returnType, HSBCPSBackVO.class)) {
                    String errorNo = errMsg.substring(0, pos);
                    String errorInfo = errMsg.substring(pos, errMsg.length() - 1);
                    return VOUtil.genErrorResult(errorNo, errorInfo, new HSBCPSBackVO());
                }
            }
        }
        return null;
    }


}
